import React from "react";
import Relay from "react-relay";
import {hashHistory} from 'react-router';
/**
 *
 *  view Component
 *
 */
import {HeaderLeft,HeaderRight} from './components/View_HeaderBtn'

import TableDetail from './components/View_TableDetail';  //表格detail

import findFinanceInvoiceList from './mutation/findFinanceInvoiceList';

import {message} from 'antd';

import './css/style.css';

import Config from "../../util/Config"
export default class A extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dataList:[],  //总数据
            tableList:[], // table处理的数据
            inOrOut: "2",   //开出或收到

            totalResult:0,    //总条数默认为0
            curPageNum:[1,1],     //当前默认的页数(包含开出和收到)

            sumInvoiceMoney:"",  //发票金额
            searchValue:"",     // 搜索的value
        };

        this.handleBtn1Click = this.handleBtn1Click.bind(this);    //btn
        this.paginationChange = this.paginationChange.bind(this);  //分页器
        this.requestTableData = this.requestTableData.bind(this);   //请求

        this.handleBtn1Click = this.handleBtn1Click.bind(this);  //切换开出开入按钮
        this.handleHeaSearch = this.handleHeaSearch.bind(this);  //搜索
        this.handleSearchChange = this.handleSearchChange.bind(this);
    }

    //asd
    handleBtn1Click(inOrOut){
        // 固定请求十条，切换开出或收到 保留上次操作的页码.
        this.setState({
            inOrOut,
            searchValue:""
        },()=>{
            this.requestTableData(this.state.curPageNum[inOrOut-1],10);
        });
    }

    // 格式校验
    textText(text){
        let R = /^[ ]*$/;
        if(text==="" || R.test(text)) { return false }else{
            return true
        }
    }

    handleHeaSearch(orderId){
        if(typeof orderId != "string" || !this.textText(orderId)){ return; }

        this.requestTableData(1,10,orderId)
    }

    heaBtnConfig = {
        className:"invoiceManage_left",
        btn1:{name:"开出", onClick:(e)=>{this.handleBtn1Click(2)},style:{marginRight:15}},
        btn2:{name:"收到", onClick:(e)=>{this.handleBtn1Click(1)}},
    };

    heaSearchConfig = {
        placeholder:"请输入订单编号",
        style:{width: 200,boxSizing:"border-box"}
    };

    componentWillMount(){}

    componentDidMount(){
        // 更新数据
        this.requestTableData(1,10);
    }

    // 请求数据并整理  table和data列表
    requestTableData(page,pageSize,orderId){
        Relay.Store.commitUpdate(
            new findFinanceInvoiceList({
                orderId:orderId || "",
                pageNum:page,
                pageSize:pageSize,
                inOrOut:this.state.inOrOut
            }),
            {
                onFailure: () => {
                    message.error("网络连接失败,请联系系统管理员");
                },
                onSuccess: (response) => {

                    let data = response.findFinanceInvoiceList.findFinanceInvoiceList,arr = [];

                    if(data.errorCode != "0"){ return }

                    const list = JSON.parse(JSON.stringify(data.financeInvoiceList));

                    const g = ["orderId","contract","invoiceMoney","product","invoiceNum","product"];

                    arr = list.map((item,index)=>{
                        const obj = {};
                        obj.key = item.orderId;

                        //根据g，赋予所需要的字段;
                        g.forEach((i,k)=>{
                            obj[i] = item[i] || "-"
                        });

                        obj["inOrOut"] = item["inOrOut"] == "2" ?"开出" : "收到";

                        return obj;
                    });
                    this.setState({dataList:list,tableList:arr,totalResult:data.totalResult,sumInvoiceMoney:data.sumInvoiceMoney});
                }
            }
        )
    }

    //发票关系
    operation(i){
        const l = this.state.dataList;
        if(l.length <= 0){ message.error("数据出现错误，请检查或刷新页面"); return;}
        const d = JSON.parse(l[i].invoiceFileJson), a = document.createElement("a");
        a.setAttribute("download","");

        Array.isArray(d) &&   d.forEach((i,k)=>{
            const h = `${Config.qiuniu+i.response.key}?attname=${i.name}`;
            a.href = h;
            a.click();
        });
    }

    //　跳转到发票树
    imvaiceTree(id){
        hashHistory.push({
            pathname:"/Invoicemanagetree/",
            state:{orderId:id}
        })
    }

    // 分页change
    paginationChange(page,pageSize){
        // 开出或收到 判别更新分页;
        this.state.curPageNum[this.state.inOrOut-1] = page;
        this.setState({
            curPageNum:this.state.curPageNum
        },()=>{
            this.requestTableData(page,pageSize)
        });
    }

    filterOrderDetil(oty,oid){
        switch (oty){
            case 0:
                return;
            case 1:
                hashHistory.push('/orderdetailgms/'+oid);
                return;
            case 2:
                hashHistory.push('/orderdetailraw/'+oid);
                return;
            case 3:
                hashHistory.push('/orderdetailcloth/'+oid);
                return;
            case 4:
                hashHistory.push('/orderdetailprint/'+oid);
                return;
            case 5:
                hashHistory.push('/orderdetailyarn/'+oid);
                return;
        }
    }

    // 跳转到订单详情
    jumpOrderDeatil(t,r,i){
        if(!t){ return; }
        const c = this.state.dataList[i].orderType;
        this.filterOrderDetil(parseInt(c),t);
    }

    // table header
    columns = [
        { title: '订单编号', dataIndex: 'orderId', key: 'orderId',render:(t,r,i)=>{
            return <a onClick={()=>this.jumpOrderDeatil(t,r,i)}> {t} </a>
        }},
        { title: '合同号', dataIndex: 'contract', key: 'contract'},
        { title: '商品类型', dataIndex: 'product', key: 'product'},
        { title: '发票金额', dataIndex: 'invoiceMoney', key: 'invoiceMoney'},
        { title: '发票张数', dataIndex: 'invoiceNum', key: 'invoiceNum'},
        { title: '类型', dataIndex: 'inOrOut', key: 'inOrOut'},
        { title: '操作', dataIndex: '', key: 'operation',render:(t,r,i)=>{
            return <span>
                     <a onClick={()=>{this.operation(i)}} style={{marginRight:15}}>下载发票</a>
                     <a onClick={()=>{this.imvaiceTree(t.orderId)}}> 发票关系明细 </a>
                </span>
        }},
    ];

    handleSearchChange(e){
        this.setState({
            searchValue:e.target.value
        })
    }

    //as
    render() {
        const {tableList,inOrOut,totalResult,sumInvoiceMoney,searchValue} = this.state;

        return(
            <div className="invoiceManage">
                <div className="invoiceManage_hea">
                    <HeaderLeft
                        key="header_left"
                        {...this.heaBtnConfig}
                        active={inOrOut}
                    />
                    <HeaderRight
                        key="header_right"
                        className="invoiceManage_right"
                        searchConf={this.heaSearchConfig}
                        onSearch={this.handleHeaSearch}
                        onChange={this.handleSearchChange}
                        value={searchValue}
                    />
                </div>
                <div className="invoiceManage_cont">
                    <header>
                        发票金额：{sumInvoiceMoney}
                    </header>
                    <TableDetail
                        columns = {this.columns}
                        data = {tableList}
                        paginationChange={this.paginationChange}
                        total={totalResult}
                        current={this.state.curPageNum[inOrOut-1]}
                    />
                </div>
            </div>
        )
    }
}